package com.miniapp.core.utils;


import com.miniapp.common.config.PaicFtiWebDriverConfig;
import com.miniapp.common.enums.PaicFtiPolicyStatus;
import com.miniapp.common.gen.domain.PaicFtiAccount;
import com.miniapp.common.gen.domain.PaicFtiAccountExample;
import com.miniapp.common.gen.domain.PaicFtiPolicy;
import com.miniapp.common.gen.mapper.PaicFtiAccountMapper;
import com.miniapp.common.gen.mapper.PaicFtiPolicyMapper;
import com.miniapp.common.utils.StringUtils;
import com.miniapp.common.utils.uuid.IdUtils;
import com.miniapp.core.domain.paicfti.PaicFtiInsureParam;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 平安货运险工具类
 */
@Component
public class PaicFtiUtils {

    private Logger logger = LoggerFactory.getLogger(PaicFtiUtils.class);

    @Autowired
    private PaicLoginUtil paicLoginUtil;

    @Autowired
    private PaicFtiInputInsuranceInfoUtils paicFtiInputInsuranceInfoUtils;

    @Autowired
    private PaicFtiSubmitInsuranceApplicationUtils paicFtiSubmitInsuranceApplicationUtils;

    @Autowired
    private PaicFtiChromeDriverUtils paicFtiChromeDriverUtils;

    @Autowired
    private PaicFtiAccountMapper paicFtiAccountMapper;

    private static Lock lock = new ReentrantLock();

    public static ThreadLocal<PaicFtiPolicy> localPaicFtiPolicy = new ThreadLocal<PaicFtiPolicy>();

    @Autowired
    private PaicFtiParamUtils paicFtiParamUtils;

    @Autowired
    private PaicFtiPolicyFileDownload paicFtiPolicyFileDownload;

    @Autowired
    private PaicFtiWebDriverConfig paicFtiWebDriverConfig;

    @Autowired
    private PaicFtiPolicyMapper paicFtiPolicyMapper;

    /**
     * 异步投保
     * @param paicFtiInsureParam 投保参数
     */
    @Async
    public void asynInsure(PaicFtiInsureParam paicFtiInsureParam  ){

        long start = System.currentTimeMillis();
        String account = paicFtiWebDriverConfig.getPaicftiAccount();
        paicFtiInsureParam.setAccount(account);

        PaicFtiAccountExample paicFtiAccountExample = new PaicFtiAccountExample();
        paicFtiAccountExample.createCriteria().andUserNameEqualTo(paicFtiInsureParam.getAccount());
        List<PaicFtiAccount> paicFtiAccountList = paicFtiAccountMapper.selectByExample(paicFtiAccountExample);
        PaicFtiAccount paicFtiAccount = paicFtiAccountList.get(0);
        String password = paicFtiAccount.getPassword();
        paicFtiInsureParam.setPassword(password);

        String uniqueId = IdUtils.simpleUUID();
        paicFtiInsureParam.setUniqueId(uniqueId);

        //0.5投保参数入库
        PaicFtiPolicy paicFtiPolicy = paicFtiParamUtils.insterParam(paicFtiInsureParam);

        //
        localPaicFtiPolicy.set(paicFtiPolicy);

        ChromeDriver webDriverScreenshot = null;
        try {
            lock.tryLock(80, TimeUnit.SECONDS);
            //1、获取投保页面的ChromeDriver
            ChromeDriver insurePageChromeDriver = paicLoginUtil.getInsurePageChromeDriver(account, password, uniqueId);
            if(insurePageChromeDriver == null ){
                insurePageChromeDriver = paicLoginUtil.getInsurePageChromeDriver(account, password, uniqueId);
            }
            webDriverScreenshot = insurePageChromeDriver;
            //2、录入投保信息
            paicFtiInputInsuranceInfoUtils.inputInsuranceInfo(paicFtiInsureParam,insurePageChromeDriver);
            //3、点击提交
            paicFtiSubmitInsuranceApplicationUtils.clickSubmit(insurePageChromeDriver);
            long end = System.currentTimeMillis();
            long l = end - start;
            l = l /1000;
            System.out.println("总用时："+l);

        }catch (Exception e){
//            if(webDriverScreenshot != null){
//                paicFtiChromeDriverUtils.webDriverScreenshot(webDriverScreenshot,account+"_"+paicFtiInsureParam.getUniqueId());
//            }
            logger.info("投保程序出现异常"+e.getMessage());
            logger.info("打印堆栈信息");
            e.printStackTrace();
            String policyStatus = paicFtiPolicy.getPolicyStatus();
            //如果是投保中的状态
            if(PaicFtiPolicyStatus.UNDER_INSURANCE.getCode().equals(policyStatus)){
                //更新为投保失败的状态
                paicFtiPolicy.setPolicyStatus(PaicFtiPolicyStatus.FAILURE_TO_INSURE.getCode());
                paicFtiPolicy.setPolicyMessage(e.getMessage());
                paicFtiPolicyMapper.updateByPrimaryKeySelective(paicFtiPolicy);
                return;
            }
//            return AjaxResult.error(e.getMessage());
        }finally {
            localPaicFtiPolicy.remove();
            lock.unlock();
        }
        String policyStatus = paicFtiPolicy.getPolicyStatus();
        String policyNo = paicFtiPolicy.getPolicyNo();
        if(PaicFtiPolicyStatus.SUCCESSFUL_INSURANCE.getCode().equals(policyStatus)){
            //异步下载电子保单
            paicFtiPolicyFileDownload.policyFileDownload(policyNo);

        }
    }

    /**
     * 通知投保结果
     */
    public void notifyPolicyResult(){

    }




}
